<template>
  <div class="package-manage-container">
    <el-card class="package-manage-card">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="搜索">
            <el-input
              v-model="searchForm.keyword"
              placeholder="套餐名称/编号"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <!-- <el-form-item label="类别">
            <el-select v-model="searchForm.category" placeholder="选择类别" clearable>
              <el-option label="婚纱摄影" value="wedding" />
              <el-option label="写真" value="portrait" />
              <el-option label="儿童摄影" value="children" />
              <el-option label="全家福" value="family" />
              <el-option label="孕妇照" value="maternity" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="选择状态" clearable>
              <el-option label="上架" value="active" />
              <el-option label="下架" value="inactive" />
              <el-option label="售罄" value="soldout" />
            </el-select>
          </el-form-item> -->
          <el-form-item label="摄影师等级">
            <el-select
              class="status-search"
              v-model="searchForm.photographer_level"
              placeholder="选择等级"
              clearable
            >
              <el-option label="初级摄影师" value="1" />
              <el-option label="高级摄影师" value="2" />
              <el-option label="资深摄影师" value="3" />
              <el-option label="首席摄影师" value="4" />
            </el-select>
          </el-form-item>
          <el-form-item label="价格区间">
            <el-input-number
              v-model="searchForm.minPrice"
              :min="0"
              :step="100"
              placeholder="最低价"
              style="width: 130px"
            />
            <span class="price-separator">-</span>
            <el-input-number
              v-model="searchForm.maxPrice"
              :min="0"
              :step="100"
              placeholder="最高价"
              style="width: 130px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
            <el-button type="success" @click="handleAdd">添加套餐</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 套餐列表 -->
      <el-table v-loading="loading" :data="packageList" style="width: 100%" border>
        <el-table-column label="套餐信息" min-width="300">
          <template #default="{ row }">
            <div class="package-info">
              <el-image
                :src="row.photos[0]"
                :preview-src-list="row.photos"
                fit="cover"
                class="package-image"
              />
              <div class="info-detail">
                <h3 class="name">{{ row.name }}</h3>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="价格信息" width="180">
          <template #default="{ row }">
            <div class="price-info">
              <div class="current-price">¥{{ row.price }}</div>
              <div class="original-price">¥{{ row.original_price }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="booking_count" label="销量" width="100" align="center" />

        <el-table-column prop="created_at" label="创建时间" width="180" />

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)"> 编辑 </el-button>
            <el-button type="success" link @click="handleViewImages(row)"> 图片管理 </el-button>
            <el-button
              :type="row.is_active ? 'danger' : 'success'"
              link
              @click="handleToggleStatus(row)"
            >
              {{ row.is_active ? '下架' : '上架' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 编辑对话框 -->
      <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑套餐' : '添加套餐'" width="800px">
        <el-form ref="formRef" :model="editForm" :rules="rules" label-width="100px">
          <el-tabs v-model="activeTab">
            <el-tab-pane label="基本信息" name="basic">
              <el-form-item label="名称" prop="name">
                <el-input v-model="editForm.name" />
              </el-form-item>

              <!-- <el-form-item label="类别" prop="category">
                <el-select v-model="editForm.category">
                  <el-option label="婚纱摄影" value="wedding" />
                  <el-option label="写真" value="portrait" />
                  <el-option label="儿童摄影" value="children" />
                  <el-option label="全家福" value="family" />
                  <el-option label="孕妇��" value="maternity" />
                </el-select>
              </el-form-item> -->

              <el-form-item label="现价" prop="price">
                <el-input-number v-model="editForm.price" :min="0" :step="100" />
              </el-form-item>

              <el-form-item label="原价" prop="original_price">
                <el-input-number v-model="editForm.original_price" :min="0" :step="100" />
              </el-form-item>

              <el-form-item label="定金" prop="deposit">
                <el-input-number v-model="editForm.deposit" :min="0" :step="100" />
              </el-form-item>

              <el-form-item label="排序" prop="sort_order">
                <el-input-number v-model="editForm.sort_order" :min="0" :max="999" />
              </el-form-item>

              <el-form-item label="摄影师等级" prop="photographer_level">
                <el-rate
                  v-model="editForm.photographer_level"
                  :max="4"
                  show-score
                  text-color="#ff9900"
                />
              </el-form-item>

              <el-form-item label="描述" prop="description">
                <el-input v-model="editForm.description" type="textarea" :rows="3" />
              </el-form-item>
            </el-tab-pane>

            <el-tab-pane label="套餐内容" name="content">
              <el-form-item label="套餐点" prop="package_gift">
                <el-input
                  v-model="featureInput"
                  placeholder="输入特点后按回车添加"
                  @keyup.enter="handleAddFeature"
                />
                <div class="tag-list">
                  <el-tag
                    v-for="(feature, index) in editForm.package_gift"
                    :key="index"
                    closable
                    @close="editForm.package_gift!.splice(index, 1)"
                  >
                    {{ feature }}
                  </el-tag>
                </div>
              </el-form-item>

              <el-form-item label="团队服务" prop="team_service">
                <el-input
                  v-model="includeInput"
                  placeholder="输入包含内容后按回车添加"
                  @keyup.enter="handleAddInclude"
                />
                <div class="tag-list">
                  <el-tag
                    v-for="(include, index) in editForm.team_service"
                    :key="index"
                    type="success"
                    closable
                    @close="editForm.team_service!.splice(index, 1)"
                  >
                    {{ include }}
                  </el-tag>
                </div>
              </el-form-item>

              <el-form-item label="影像产品" prop="image_product">
                <el-input
                  v-model="excludeInput"
                  placeholder="输入不含内容后按回车添加"
                  @keyup.enter="handleAddExclude"
                />
                <div class="tag-list">
                  <el-tag
                    v-for="(exclude, index) in editForm.image_product"
                    :key="index"
                    type="danger"
                    closable
                    @close="editForm.image_product!.splice(index, 1)"
                  >
                    {{ exclude }}
                  </el-tag>
                </div>
              </el-form-item>

              <el-form-item label="温馨提示" prop="tips">
                <el-input
                  v-model="noticeInput"
                  placeholder="输入注意事项后按回车添加"
                  @keyup.enter="handleAddNotice"
                />
                <div class="tag-list">
                  <el-tag
                    v-for="(notice, index) in editForm.tips"
                    :key="index"
                    type="warning"
                    closable
                    @close="editForm.tips!.splice(index, 1)"
                  >
                    {{ notice }}
                  </el-tag>
                </div>
              </el-form-item>
            </el-tab-pane>
          </el-tabs>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSave" :loading="saveLoading"> 保存 </el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 图片管理对话框 -->
      <el-dialog v-model="imagePreviewDialogVisible">
        <img w-full :src="imagePreviewDialogImageUrl" alt="Preview Image" />
      </el-dialog>

      <el-dialog v-model="imageDialogVisible" title="图片管理" width="800px">
        <div v-loading="uploadLoading" class="upload-container">
          <el-upload
            class="image-uploader"
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-change="handleImageChange"
            :before-upload="beforeUpload"
            :file-list="photosList"
            multiple
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="imageDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSaveImages" :loading="saveLoading">
              保存
            </el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { Package, PackageQuery } from '@/types/package'
import {
  createPackage,
  getPackageList,
  updatePackage,
  updatePackagePhotos,
  updatePackageSort,
  updatePackageStatus,
} from '@/api/package'
import type { FormInstance, FormRules, UploadUserFile } from 'element-plus'
import { beforeUpload } from '@/utils/upload'
import type { FileItem, UploadFile } from '@/types/upload'
import { v4 as uuidv4 } from 'uuid'
import { uploadPackageImages } from '@/api/upload'
import Logger from '@/utils/logger'

// 搜索表单
const searchForm = reactive<PackageQuery>({
  keyword: '',
  photographer_level: undefined,
  minPrice: undefined,
  maxPrice: undefined,
  page: 1,
  pageSize: 10,
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 加载状态
const loading = ref(false)
const saveLoading = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const imageDialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()
const activeTab = ref('basic')
const imagePreviewDialogImageUrl = ref('')
const imagePreviewDialogVisible = ref(false)

// 图片管理相关
const uploadLoading = ref(false)
const photosList = ref<UploadUserFile[]>([])

// 输入框临时变量
const featureInput = ref('')
const includeInput = ref('')
const excludeInput = ref('')
const noticeInput = ref('')

// 编辑表单
const editForm = reactive<Partial<Package>>({
  name: '',
  description: '',
  price: 0,
  original_price: 0,
  deposit: 0,
  photographer_level: 1,
  photos: [],
  package_gift: [],
  team_service: [],
  image_product: [],
  tips: [],
  sort_order: 0,
})

// 表单验证规则
const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入套餐名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
  ],
  price: [{ required: true, message: '请输入现价', trigger: 'blur' }],
  original_price: [{ required: true, message: '请输入原价', trigger: 'blur' }],
  description: [{ required: true, message: '请输入描述', trigger: 'blur' }],
  package_gift: [{ required: true, message: '请输入套餐点', trigger: 'blur' }],
  team_service: [{ required: true, message: '请输入团队服务', trigger: 'blur' }],
  image_product: [{ required: true, message: '请输入影像产品', trigger: 'blur' }],
  tips: [{ required: true, message: '请输入温馨提示', trigger: 'blur' }],
})

// 套餐列表数据
const packageList = ref<Package[]>([
  // {
  //   id: 1,
  //   name: '浪漫海景婚纱套餐',
  //   code: 'PKG001',
  //   category: 'wedding',
  //   description: '三亚蜜月湾外景拍摄，赠送精美相册',
  //   details: ['8小时拍摄', '30张精修片', '1本12寸相册'],
  //   price: 3999,
  //   originalPrice: 5999,
  //   images: ['/src/assets/package1.jpg', '/src/assets/package1-1.jpg'],
  //   features: ['海景', '专业团队', '赠送相册'],
  //   includes: ['化妆造型', '服装租赁', '场地费用'],
  //   excludes: ['交通费用', '住宿费用'],
  //   notice: ['提前3天预约', '不可退款'],
  //   status: 'active',
  //   sort: 1,
  //   sales: 28,
  //   createTime: '2024-03-01',
  //   updateTime: '2024-03-01',
  // },
  // {
  //   id: 2,
  //   name: '森系小清新写真套餐',
  //   code: 'PKG002',
  //   category: 'portrait',
  //   description: '春日里的小清新写真，赠送精美相框',
  //   details: ['4小时拍摄', '20张精修片', '2个相框'],
  //   price: 1999,
  //   originalPrice: 2999,
  //   images: ['/src/assets/package2.jpg', '/src/assets/package2-1.jpg'],
  //   features: ['森系', '小清新', '赠送相框'],
  //   includes: ['化妆造型', '服装租赁'],
  //   excludes: ['交通费用'],
  //   notice: ['提前2天预约'],
  //   status: 'active',
  //   sort: 2,
  //   sales: 35,
  //   createTime: '2024-03-02',
  //   updateTime: '2024-03-02',
  // },
])

// 获取分类标签类型
// const getCategoryTagType = (category: PackageCategory) => {
//   const types: Record<PackageCategory, string> = {
//     wedding: 'danger',
//     portrait: 'warning',
//     children: 'success',
//     family: 'info',
//     maternity: 'primary',
//   }
//   return types[category]
// }

// 获取分类标签文本
// const getCategoryLabel = (category: PackageCategory) => {
//   const labels: Record<PackageCategory, string> = {
//     wedding: '婚纱摄影',
//     portrait: '写真',
//     children: '儿童摄影',
//     family: '全家福',
//     maternity: '孕妇照',
//   }
//   return labels[category]
// }

// 获取状态标签类型
// const getStatusTagType = (status: PackageStatus) => {
//   const types: Record<PackageStatus, string> = {
//     active: 'success',
//     inactive: 'info',
//     soldout: 'danger',
//   }
//   return types[status]
// }

// 获取状态标签文本
// const getStatusLabel = (status: PackageStatus) => {
//   const labels: Record<PackageStatus, string> = {
//     active: '上架',
//     inactive: '下架',
//     soldout: '售罄',
//   }
//   return labels[status]
// }

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = ''
  searchForm.photographer_level = undefined
  searchForm.minPrice = undefined
  searchForm.maxPrice = undefined
  handleSearch()
}

// 处理分页
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchData()
}

// 添加套餐
const handleAdd = () => {
  isEdit.value = false
  Object.assign(editForm, {
    name: '',
    description: '',
    price: 0,
    original_price: 0,
    deposit: 0,
    photographer_level: 1,
    photos: [],
    package_gift: [],
    team_service: [],
    image_product: [],
    tips: [],
    sort_order: 0,
  })
  dialogVisible.value = true
}

// 编辑套餐
const handleEdit = (row: Package) => {
  isEdit.value = true
  Object.assign(editForm, {
    id: row.id,
    name: row.name,
    description: row.description,
    price: row.price,
    original_price: row.original_price,
    deposit: row.deposit,
    photographer_level: row.photographer_level,
    photos: [...row.photos],
    package_gift: [...row.package_gift],
    team_service: [...row.team_service],
    image_product: [...row.image_product],
    tips: [...row.tips],
    sort_order: row.sort_order,
  })
  dialogVisible.value = true
}

// MARK: 图片管理
// 查看图片
const handleViewImages = (row: Package) => {
  editForm.id = row.id
  // 将现有图片转换为 UploadUserFile 格式
  if (row.photos) {
    photosList.value = row.photos?.map((url, index) => {
      return {
        name: `图片${index + 1}`,
        url: url,
      } as UploadUserFile
    })
  }
  imageDialogVisible.value = true
}

// 处理图片上传
const handleImageChange = (file: UploadFile) => {
  if (!beforeUpload(file.raw)) return

  // 创建预览URL
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = async () => {
    const newFile: FileItem = {
      uid: uuidv4(),
      name: file.name,
      url: reader.result as string,
      status: 'ready',
      raw: file.raw,
    }

    try {
      if (!newFile.raw) {
        ElMessage.error('请选择文件')
        return
      }

      newFile.status = 'uploading'
      newFile.percentage = 0

      const response = await uploadPackageImages([newFile.raw], (percentage) => {
        newFile.percentage = percentage
      })

      newFile.status = 'success'
      photosList.value.push({
        name: response.data.data.files[0].filename,
        url: response.data.data.files[0].url,
      } as UploadUserFile)
      ElMessage.success('上传成功')
    } catch (error) {
      newFile.status = 'error'
      ElMessage.error('上传失败')
      Logger.error('上传失败', error)
    }
  }
}

const handleRemove = (file: UploadUserFile) => {
  const index = photosList.value.findIndex((item) => item.url === file.url)
  if (index > -1) {
    photosList.value.splice(index, 1)
  }
}

const handlePictureCardPreview = (file: UploadUserFile) => {
  imagePreviewDialogImageUrl.value = file.url!
  imagePreviewDialogVisible.value = true
}

// 保存图片
const handleSaveImages = async () => {
  saveLoading.value = true
  try {
    const uploadPhotos = photosList.value.map((item) => item.url!)
    const response = await updatePackagePhotos(editForm.id!, {
      photos: uploadPhotos,
    })
    Logger.info('保存图片成功', response)
    ElMessage.success('保存成功')
    imageDialogVisible.value = false
    fetchData()
  } catch (error) {
    Logger.error('保存图片失败', error)
    ElMessage.error('保存失败')
  } finally {
    saveLoading.value = false
  }
}

// 切换状态
const handleToggleStatus = async (row: Package) => {
  try {
    await ElMessageBox.confirm(`确定要${row.is_active ? '下架' : '上架'}该套餐吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await updatePackageStatus(row.id)
    ElMessage.success('操作成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 处理排序变更
const handleSortChange = async (row: Package) => {
  // try {
  //   await updatePackageSort(row.id, row.sort_order)
  //   ElMessage.success('排序更新成功')
  //   fetchData()
  // } catch (error) {
  //   if (error !== 'cancel') {
  //     ElMessage.error('排序更新失败')
  //   }
  // }
}

// 添加特点
const handleAddFeature = () => {
  if (featureInput.value) {
    editForm.package_gift = editForm.package_gift || []
    editForm.package_gift.push(featureInput.value)
    featureInput.value = ''
  }
}

// 添加包含内容
const handleAddInclude = () => {
  if (includeInput.value) {
    editForm.team_service = editForm.team_service || []
    editForm.team_service.push(includeInput.value)
    includeInput.value = ''
  }
}

// 添加不含内容
const handleAddExclude = () => {
  if (excludeInput.value) {
    editForm.image_product = editForm.image_product || []
    editForm.image_product.push(excludeInput.value)
    excludeInput.value = ''
  }
}

// 添加注意事项
const handleAddNotice = () => {
  if (noticeInput.value) {
    editForm.tips = editForm.tips || []
    editForm.tips.push(noticeInput.value)
    noticeInput.value = ''
  }
}

// 保存套餐信息
const handleSave = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      saveLoading.value = true
      if (isEdit.value) {
        try {
          await updatePackage(editForm.id!, {
            name: editForm.name,
            description: editForm.description,
            price: Number(editForm.price),
            original_price: Number(editForm.original_price),
            photographer_level: Number(editForm.photographer_level),
            photos: editForm.photos,
            package_gift: editForm.package_gift,
            team_service: editForm.team_service,
            image_product: editForm.image_product,
            tips: editForm.tips,
            sort_order: Number(editForm.sort_order),
            deposit: Number(editForm.deposit),
          })

          ElMessage.success('保存成功')
          dialogVisible.value = false
          fetchData()
        } catch (error) {
          ElMessage.error('保存失败')
        } finally {
          saveLoading.value = false
        }
      } else {
        try {
          await createPackage({
            name: editForm.name!,
            description: editForm.description!,
            price: editForm.price!,
            original_price: editForm.original_price!,
            photographer_level: editForm.photographer_level!,
            photos: editForm.photos || [],
            package_gift: editForm.package_gift || [],
            team_service: editForm.team_service || [],
            image_product: editForm.image_product || [],
            tips: editForm.tips || [],
            sort_order: editForm.sort_order!,
            deposit: editForm.deposit!,
          })

          ElMessage.success('创建套餐成功')
          dialogVisible.value = false
          fetchData()
        } catch (error) {
          ElMessage.error('创建套餐失败')
        } finally {
          saveLoading.value = false
        }
      }
    }
  })
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const { data } = await getPackageList({
      keyword: searchForm.keyword,
      photographer_level: searchForm.photographer_level,
      minPrice: searchForm.minPrice,
      maxPrice: searchForm.maxPrice,
      page: currentPage.value,
      pageSize: pageSize.value,
    })
    packageList.value = data.data.items
    total.value = data.data.meta.total
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.package-manage-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  min-height: calc(100vh - 200px);
  box-sizing: border-box;
}

.package-manage-card {
  margin-top: 0;
}

.search-bar {
  margin-bottom: 20px;
}

.price-separator {
  margin: 0 10px;
}

.package-info {
  display: flex;
  gap: 15px;
}

.package-image {
  width: 100px;
  height: 100px;
  border-radius: 4px;
}

.info-detail {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.name {
  margin: 0;
  font-size: 16px;
}

.code {
  color: #666;
  font-size: 13px;
}

.price-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.current-price {
  color: #f56c6c;
  font-size: 16px;
  font-weight: bold;
}

.original-price {
  color: #999;
  text-decoration: line-through;
  font-size: 13px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.tag-list {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.image-uploader {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

:deep(.el-upload--picture-card) {
  width: 150px;
  height: 150px;
  line-height: 150px;
}

.status-search {
  width: 120px;
}
</style>
